package controller.ur;

import java.io.File;
import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import controller.CUtil;

import model.dao.PhotoDaoLocal;
import model.entity.Album;
import model.entity.Photo;

/**
 * Servlet implementation class SPhotoDelete
 */
public class SPhotoDelete extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@EJB
	private PhotoDaoLocal photoDao;
	
	private Logger log=Logger.getLogger(SPhotoDelete.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SPhotoDelete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		
		Integer photoId=Integer.parseInt((String) request.getParameter("photoId"));
		Photo photo=photoDao.findById(photoId);
		
		Integer albumId=0;
		for(Album album:photo.getAlbums()){
			if(!album.getFavorite()){
				albumId=album.getId();
				break;
			}
		}
		photoDao.removePhotoAlbums(photoId);
		File file=new File(getServletContext().getRealPath("")+photo.getLocation());
		file.delete();
		file=new File(getServletContext().getRealPath("")+photo.getThumbnailLocation());
		file.delete();
		log.info("Photo deleted: "+photo.toString());
		photoDao.remove(photo);
		CUtil.redirecter(request, response, "/SViewAlbum?albumId="+albumId);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
